﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.Office.Server.UserProfiles;
using System.Linq;
using System.Data;


namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Salary_Advance_Print : LayoutsPageBase
    {

        SPHelper obj = new SPHelper();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string TicketNo;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string AdvanceDetails;

        public static string lstGuid { get; set; }
        public string camlQry;
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;

        public static string AdvRequestNo;

        public static int wfOrder = 0;

        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        string[] buttonVisibilty = new string[5];

        Label EmpName; Label EmpID; Label Division; Label Department; Label Designation; Label MobNo;

        SPListItem oItem = null;
        SPListItemCollection oItemColl = null;
        SPQuery qry;

        public static SPFieldUserValue fldSubmittedFor = null;

        #endregion

        public Salary_Advance_Print()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Salary Advance Forms";
            TaskLstName = "Salary Advance Tasks";
            CmntsLstName = "Salary Advance Comments";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";
            AdvanceDetails = "Advance Details";

        }

        #region "User control manipulation"
        /// <summary>
        /// Get user control controls using find control method 
        /// </summary>
        private void GetUserControls()
        {
            EmpName = userInfo.FindControl("lblEmpName") as Label;
            EmpID = userInfo.FindControl("lblEmpID") as Label;
            Division = userInfo.FindControl("lblDivision") as Label;
            Department = userInfo.FindControl("lblDepartment") as Label;
            Designation = userInfo.FindControl("lblDesignation") as Label;
            MobNo = userInfo.FindControl("lblMobNo") as Label;
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                Mode = Request.QueryString["Mode"];
                if (!IsPostBack)
                {
                    if (Mode == "Print" || Mode == "View")
                    {
                        ReLoadDetails();
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Salary Advance Form" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Function to bind data after the Form gets submitted.
        /// </summary>
        /// <param name="SiteURL"></param>

        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                string RefNo = Convert.ToString(Request.Params["RefID"]);

                camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + RefNo + "</Value></Eq></Where>";
                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {
                    lblSalAdvReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtpDate.Text = Convert.ToDateTime(lstDatas["RequestDate"]).ToString("dd/MM/yyyy");

                    Label lblFormID = userInfo.FindControl("lblFormID") as Label;
                    lblFormID.Text = lstDatas.ParentList.ID.ToString();

                    submittedfor = Convert.ToString(lstDatas["SubmittedFor"]);
                    SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
                    fldSubmittedFor = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
                    submittedfor = fldUser.LookupValue;

                    if (Convert.ToString(lstDatas["OnBehalfof"]) == "Yes")
                    {
                        lblOnBehalf.Text = "On Behalf of";
                        pnlReqEmpInf.Visible = true;
                        SetValuestoOnBehalfof(lstDatas);
                    }

                    else
                    {
                        lblOnBehalf.Text = "Logged in User";
                    }

                    string user = Convert.ToString(lstDatas["SubmittedFor"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["DateofEmployment"])))
                        dtDOE.Text = Convert.ToDateTime(lstDatas["DateofEmployment"]).ToString("dd/MM/yyyy"); ;

                    txtBasicSalary.Text = Convert.ToString(lstDatas["BasicSalary"]);
                    txtAdvance.Text = Convert.ToString(lstDatas["AdvanceAmount"]);
                    txtInstalment.Text = Convert.ToString(lstDatas["Instalment"]);
                    txtDeduction.Text = Convert.ToString(lstDatas["DeductionAmount"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["StartsOn"])))
                        dtStDate.Text = Convert.ToDateTime(lstDatas["StartsOn"]).ToString("dd/MM/yyyy"); ; ;

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["EndsOn"])))
                        dtEndDate.Text = Convert.ToDateTime(lstDatas["EndsOn"]).ToString("dd/MM/yyyy"); ; ;

                    txtOS.Text = Convert.ToString(lstDatas["OSAmount"]);
                    txtTotOS.Text = Convert.ToString(lstDatas["TtlOSAmount"]);

                    GetApprovedUsers(RefNo);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        #region "Set Values to OnBehalfof"

        private void SetValuestoOnBehalfof(SPListItem lstDatas)
        {
            SPFieldUserValue user = new SPFieldUserValue(SPContext.Current.Web, lstDatas["SubmittedFor"].ToString());
            //setPeopleEditors(user, pplReqUser);

            pplReqUser.Visible = false;
            txtReqUser.Visible = true; 
            txtReqUser.Text = user.LookupValue.ToString();
            txtReqEmpId.Text = Convert.ToString(lstDatas["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(lstDatas["Division"]);
            txtReqDept.Text = Convert.ToString(lstDatas["Department"]);
            txtReqDesignation.Text = Convert.ToString(lstDatas["Designation"]);
            txtReqMobileNo.Text = Convert.ToString(lstDatas["MobileNo"]);
            txtReqMobileNo.Enabled = false;
        }

        #endregion


        private void GetApprovedUsers(string refNo)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = obj.GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }

    }
}
